package com.zyt.aop;

import com.zyt.mapper.OperateLogMapper;
import com.zyt.pojo.Emp;
import com.zyt.pojo.EmpLoginLog;
import com.zyt.pojo.LoginInfo;
import lombok.extern.slf4j.Slf4j;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.lang.invoke.StringConcatFactory;
import java.time.LocalDate;
import java.time.LocalDateTime;

@Slf4j
@Component
@Aspect//说明这是一个AOp切面类
public class RecordLogMessage {
    @Autowired
    private OperateLogMapper operateLogMapper;

    @Around("execution(* com.zyt.service.Impl.EmpServiceImpl.login(..))")
    public Object RecordLog(ProceedingJoinPoint joinPoint) throws Throwable {
        log.info("记录登录日志");
        Object result = joinPoint.proceed();
        Emp emp = (Emp) joinPoint.getArgs()[0];
        Long start = System.currentTimeMillis();

        LocalDateTime loginTime = LocalDateTime.now();
        Long end = System.currentTimeMillis();

        //创建日志对象
        EmpLoginLog empLoginLog = new EmpLoginLog();

        empLoginLog.setUsername(emp.getUsername());
        empLoginLog.setPassword(emp.getPassword());
        empLoginLog.setLoginTime(loginTime);
        empLoginLog.setCostTime(start -  end);
        if (result instanceof LoginInfo) {
            LoginInfo info = (LoginInfo) result;
            empLoginLog.setIsSuccess((short) 1);
            empLoginLog.setJwt(info.getToken());
            operateLogMapper.insertLog(empLoginLog);

        } else {
            empLoginLog.setIsSuccess((short) 0);
            empLoginLog.setJwt(null);
            operateLogMapper.insertLog(empLoginLog);

        }
        return result;
    }


}
